package com.explodingzombie.util;

import java.util.ArrayList;
import java.util.List;


import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import com.explodingzombie.util.RssItem;

public abstract class RssHandler extends DefaultHandler {
	
	protected String DATA_TAG = "item";

	protected List<RssItem> items;
	protected StringBuilder builder;
	protected RssItem currentItem;
	
	public List<RssItem> getItems(){
		return items;
	}
	
	@Override
	public void startDocument() throws SAXException
	{
		super.startDocument();
		items = new ArrayList<RssItem>();
		builder = new StringBuilder();
	}
	
    @Override
    public void characters(char[] ch, int start, int length)
            throws SAXException {
        super.characters(ch, start, length);
        builder.append(ch, start, length);
    }
	
	@Override
	public void startElement(String uri, String localName, String name, Attributes attributes)
		throws SAXException
	{
		super.startElement(uri, localName, name, attributes);
		if(localName.equalsIgnoreCase(this.DATA_TAG)){
			this.currentItem = new RssItem();
			builder.setLength(0);
		}
	}
	
	@Override
	public void endElement(String uri, String localName, String name) throws SAXException
	{
		super.endElement(uri, localName, name);
		if(localName.equalsIgnoreCase(this.DATA_TAG)){
			items.add(currentItem);
		}
	}
	
}
